<template>
    <div class="chart" ref="chartRef">
    </div>
</template>
<script setup>
import * as echarts from 'echarts'
import { ref, watch, onMounted,onActivated } from 'vue'

const props = defineProps({
    xData: {
        type: Array
    },
    yData: {
        type: Array
    },
    colorType: {
        type: String,
        default: 'blue'
    },
    data: {
        type: Array
    }
})

const chartRef = ref(null)
const chartBarRef = ref(null)
const myChart = ref(null)

const date = []
const data = []

const colorMap = {
    blue: {
        base: 'rgba(12, 83, 252, 1)',
        start: 'rgba(12, 83, 252, 0.2)',
        end: 'rgba(12, 83, 252, 0)'
    },
    green: {
        base: 'rgba(73, 195, 150, 1)',
        start: 'rgba(73, 195, 150, 0.29)',
        end: 'rgba(73, 195, 150, 0)'
    }
}

const createOption = (data) => {
    const chartOption =
    {
        grid: {
            left: 0,
            right: 0,
            top: 0,
            bottom: 10
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            show: false,
            data: date,
            axisLine: {
                show: false
            }
        },
        yAxis: {
            type: 'value',
            show: false,
            boundaryGap: [0, '100%'],
            splitLine: {
                lineStyle: {
                    type: 'none'
                }
            }
        },
        series: [
            {
                name: '数据',
                type: 'line',
                symbol: 'none',
                sampling: 'lttb',
                smooth: true,
                itemStyle: {
                    color: colorMap[props.colorType].base
                },
                areaStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        {
                            offset: 0,
                            color: colorMap[props.colorType].start
                        },
                        {
                            offset: 1,
                            color: colorMap[props.colorType].end
                        }
                    ])
                },
                data: data
            }
        ]
    }
    return chartOption
}



const setOption = (data) => {
    console.log(45555555, data)
    myChart.value.setOption(createOption(data))
}

const resize = () => {
    myChart.value.resize()
}

defineExpose({
    chartBarRef,
    resize
})

watch(() => props.data, (newval) => {
    if (newval) {
        setTimeout(() => {
            setOption(newval)
        }, 0)
    }
}, {
    immediate: true,
    deep: true
})

onMounted(() => {
    myChart.value = echarts.init(chartRef.value)
})
onActivated(() => {
    myChart.value = echarts.init(chartRef.value)
})
</script>
<style lang="scss" scoped>
.chart {
    width: 100%;
    height: 100%;
}
</style>